;; 测试 call-with-current-continuation (call/cc) 功能

;; 测试1: 基本的continuation使用
(display "测试1: 基本的continuation使用\n")
(define result1
  (call/cc
   (lambda (cont)
     (display "调用continuation前\n")
     (cont 42)  ;; 这会立即返回到call/cc调用点
     (display "这一行不会被执行\n")
     0)))  ;; 这个值永远不会被使用
(display "结果: ")
(display result1)
(display "\n\n")

;; 测试2: 从深层嵌套函数中提前返回
(display "测试2: 从深层嵌套函数中提前返回\n")
(define result2
  (call/cc
   (lambda (exit)
     (define (deeply-nested x)
       (if (> x 10)
           (exit "超出限制！")
           (deeply-nested (+ x 1))))
     (deeply-nested 0)
     "这不会被返回")))
(display "结果: ")
(display result2)
(display "\n\n")

;; 测试3: 创建一个简单的非确定性计算
(display "测试3: 创建一个简单的非确定性计算\n")
(define result3 '())
(define (amb choices)
  (if (null? choices)
      #f
      (call/cc
       (lambda (cc)
         (set! choices (cons (lambda () (cc (car choices))) (cdr choices)))
         (car choices)))))

(define (fail)
  (if (null? choices)
      (error "没有更多的选择")
      ((car choices))))

(let ((choices '()))
  (call/cc
   (lambda (k)
     (set! choices '())
     (set! result3 (amb '(1 2 3 4 5)))
     (k #t))))
(display "结果: ")
(display result3)
(display "\n\n")

;; 测试4: 使用call/cc实现循环
(display "测试4: 使用call/cc实现循环\n")
(define (loop start end body)
  (call/cc
   (lambda (break)
     (let ((i start))
       (call/cc
        (lambda (continue)
          (define (iter)
            (if (> i end)
                (break #f)
                (begin
                  (body i)
                  (set! i (+ i 1))
                  (continue #f))))  ;; 继续下一次迭代
          (iter)))))))

(display "计数: ")
(loop 1 5 
      (lambda (n)
        (display n)
        (display " ")))
(display "\n\n")

;; 测试5: 创建一个可以多次调用的continuation
(display "测试5: 创建一个可以多次调用的continuation\n")
(define the-continuation #f)
(define result4 '())

(let ((value (call/cc
              (lambda (cont)
                (set! the-continuation cont)
                0))))
  (set! result4 (append result4 (list value))))

(display "首次调用后: ")
(display result4)
(display "\n")

;; 调用保存的continuation
(the-continuation 1)
(display "第二次调用后: ")
(display result4)
(display "\n")

(the-continuation 2)
(display "第三次调用后: ")
(display result4)
(display "\n\n")

;; 测试6: 实现异常处理
(display "测试6: 实现异常处理\n")
(define exception-handler #f)

(define (with-exception-handler handler thunk)
  (let ((old-handler exception-handler))
    (set! exception-handler handler)
    (let ((result (thunk)))
      (set! exception-handler old-handler)
      result)))

(define (raise exception)
  (if exception-handler
      (exception-handler exception)
      (error "未捕获的异常: " exception)))

(define result5
  (with-exception-handler
   (lambda (e)
     (display "捕获到异常: ")
     (display e)
     (display "\n")
     'exception-handled)
   (lambda ()
     (display "正常执行中...\n")
     (raise "测试异常")
     (display "这一行不会被执行\n")
     'normal-return)))

(display "结果: ")
(display result5)
(display "\n\n")

(display "所有测试完成！\n")